package kr.co.webmill.sqlite;

import java.util.ArrayList;
import java.util.List;

import kr.co.webmill.testdatabase.Comment;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CommentsDataSource {
	// fields
	private SQLiteDatabase database;
	private DbSqliteHelper helper;
	private String[] allColumns = {DbSqliteHelper.COLUMN_ID, DbSqliteHelper.COLUMN_COMMENT}; 
	
	public CommentsDataSource(Context context){
		helper = new DbSqliteHelper(context);
	}
	public void open() throws SQLException {
		database = helper.getWritableDatabase();
	}
	
	public void close(){
		helper.close();
	}
	
	public Comment createComment(String comment){
		ContentValues values = new ContentValues();
		values.put(helper.COLUMN_COMMENT, comment);
		long insertId = database.insert(helper.TABLE_COMMENTS, null, values);
		Cursor cursor = database.query(helper.TABLE_COMMENTS, allColumns, 
				(helper.COLUMN_ID + "=" + insertId) , 
				null, null, null, null);
		cursor.moveToFirst();
		Comment newComment = cursorToComment(cursor);
		cursor.close();
		return newComment;
	}
	/*
	public Comment comment(Cursor cursor){
		Comment comment = new Comment();
		comment.setId(cursor.getLong(0));
		comment.setComment(cursor.getString(1));
		return comment;
	}
	*/
	public void deleteComment(Comment comment){
		long id = comment.getId();
		System.out.println(" " + id + " comment is deleting");
		database.delete(helper.TABLE_COMMENTS, helper.COLUMN_ID + "=" + id , null);
	}
	public List<Comment> getAllComments(){
		List<Comment> comments = new ArrayList<Comment>();
		Cursor cursor = database.query(helper.TABLE_COMMENTS, allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while(cursor.isAfterLast() == false){
			comments.add(cursorToComment(cursor));
		}
		cursor.close();
		return comments;
	}
	
	private Comment cursorToComment(Cursor cursor){
		Comment comment = new Comment();
		comment.setId(cursor.getLong(0));
		comment.setComment(cursor.getString(1));
		return comment;		
	}

}
